import { ETaskState } from "GameLoop/DecisionMaking/TaskDeclare/type";
 
export class TowerTaskChecker
{
    public static notify:Notify
    public static check(room:Room,task:ITaskDeclare["tower"])
    {
        switch(task.data.type)
        {
            case "towerDefend":
                return this.checkTowerDefend(room,task as any);
            case "towerRepair":
                return this.checkTowerRepair(room,task as any);
            case "towerHeal":
                return this.checkTowerHeal(room,task as any);
        }
    }
    static checkTowerHeal(room: Room,   task:ITask<IRoomTaskData<"towerHeal">>) 
    {
       
        const creeps=room.getHurtCreeps();
        if(creeps.length ==0)
        {
            return ETaskState.Complete;
        }
        task.data.arg.Creeps = creeps.map(e=>e.name);
        return ETaskState.Running;
    }
    
    private static checkTowerDefend(room:Room,task:ITask<IRoomTaskData<"towerDefend">>):ETaskState
    {
        const hostiles = room.getWorld().PollHostiles(room.name);
        if(room.memory.warinfo)
        {
            for(let i=0;i<room.memory.warinfo.enemy.length;)
            {
                const creep  = Game.getObjectById(room.memory.warinfo.enemy[i]);
                if(!creep)
                {
                    room.memory.warinfo.enemy.splice(i,1);
                }
                else
                {
                    i++
                }
            }
        }
        const enemy:Id<Creep>[] = [];
        if(hostiles && hostiles.cacheData.length>0 )
        {
            for(let e of hostiles.cacheData)
            {
                const creep  = Game.getObjectById(e.id);
                if(creep)
                {
                    enemy.push(creep.id);
                }
            }
        }
        room.memory.warinfo = {enemy :enemy};
        if(enemy.length==0)
        {
            room.memory.warinfo=undefined
            return ETaskState.Complete;
        }
         
        return ETaskState.Running;
    }

    private static checkTowerRepair(room:Room,task:ITask<IRoomTaskData<"towerRepair">>):ETaskState
    {
        const structurekeys = Object.keys(task.data.arg.targets);
        let count=0;
        for(let k of structurekeys)
        {
            const obj = Game.getObjectById(k as Id<AnyStructure>);
            if(!obj || obj.hits>= task.data.arg.targets[k as Id<AnyStructure>])
            {
                delete task.data.arg.targets[k as Id<AnyStructure>];
            }
            else
            {
                count++;
               // room.log("info","防御塔维修状态",`${obj.hits}<${task.data.arg.targets[k as Id<AnyStructure>]}`)
            }
        }
        if(count==0)
        {
            return ETaskState.Complete;
        }
        // room.log("info","防御塔维修状态",JSON.stringify(Object.keys(task.data.arg.targets)))
        return ETaskState.Running;
    }
 
}